import fs from 'fs';
import path from 'path';
import dayjs from 'dayjs';
import FsDriver from './FsDriver.js';
import { split_index } from '../config/dltconfig.js';
const fsDriver = new FsDriver();

class DltModel {
    getData() {
        let filePath = path.join(import.meta.dirname, '../data/dlt/data/data.json');
        return fs.existsSync(filePath) ? JSON.parse(fs.readFileSync(filePath)) : [];
    }

    buildStat() {
        const data = this.getData();
        let frontStat = {}, backStat = {}, columnStat = [{}, {}, {}, {}, {}, {}, {}];
        let frontStatSorted = {}, backStatSorted = {}, columnStatSorted = [{}, {}, {}, {}, {}, {}, {}];
        let isFront = true; // 是否是前区号码
        data.forEach((row, x) => {
            row.lotteryDrawResult.split(' ').forEach((num, i) => {
                isFront = i < split_index;
                if (isFront) {
                    frontStat[num] = frontStat[num] ? frontStat[num] + 1 : 1;
                } else {
                    backStat[num] = backStat[num] ? backStat[num] + 1 : 1;
                }
                columnStat[i][num] = columnStat[i][num] ? columnStat[i][num] + 1 : 1;
            });
        });
        // 排序
        Object.keys(frontStat).sort().forEach(key => {
            frontStatSorted['N' + key] = frontStat[key];
        });
        Object.keys(backStat).sort().forEach(key => {
            backStatSorted['N' + key] = backStat[key];
        });
        frontStat = null;
        backStat = null;
        columnStat.forEach((statObj, i) => {
            let statSorted = {};
            Object.keys(statObj).sort().forEach(key => {
                statSorted['N' + key] = statObj[key];
            });
            columnStatSorted[i] = statSorted;
        });
        columnStat = null;
        return { frontStat: frontStatSorted, backStat: backStatSorted, columnStat: columnStatSorted };
    }
    saveStat() {
        const { frontStat, backStat, columnStat } = this.buildStat();
        let filePath = path.join(import.meta.dirname, '../data/dlt/data/stat.json');
        fs.writeFileSync(filePath, JSON.stringify({ frontStat, backStat, columnStat }));

        let data = {}, key = '';

        for (let num in frontStat) {
            for (let i = 1; i <= 3; i++) {
                key = 'front-ge' + i;
                if (!data[key]) {
                    data[key] = [];
                }
                if (frontStat[num] >= i) {
                    data[key].push(num);
                }
            }
        }
        for (let num in backStat) {
            for (let i = 1; i <= 3; i++) {
                key = 'back-ge' + i;
                if (!data[key]) {
                    data[key] = [];
                }
                if (backStat[num] >= i) {
                    data[key].push(num);
                }
            }
        }
        columnStat.forEach((statObj, idx) => {
            idx += 1;
            for (let num in statObj) {
                for (let i = 1; i <= 3; i++) {
                    key = 'col' + idx + '-ge' + i;
                    if (!data[key]) {
                        data[key] = [];
                    }
                    if (statObj[num] >= i) {
                        data[key].push(num);
                    }
                }
            }
        });

        filePath = path.join(import.meta.dirname, '../data/dlt/data/statlite.json');
        fs.writeFileSync(filePath, JSON.stringify(data));
    }
    generateOrder(onlyColumn = true, level = 1) {
        const statLiteData = JSON.parse(fs.readFileSync(path.join(import.meta.dirname, '../data/dlt/data/statlite.json')));
        let data = [], key = '';
        if (onlyColumn) {
            for (let i = 1; i <= 7; i++) {
                key = `col${i}-ge${level}`;
                data.push(statLiteData[key][Math.floor(Math.random() * statLiteData[key].length)]);
            }
            return data;
        }
        data = [...statLiteData[`front-ge${level}`]].sort(() => 0.5 - Math.random()).slice(0, 5).sort();
        return data.join([...statLiteData[`back-ge${level}`]].sort(() => 0.5 - Math.random()).slice(0, 5).sort());
    }

    saveOrder(issue = '') {
        let drawalInfo = null, historyData = this.getData();
        if (issue) {
            let prevIssue = parseInt(issue) - 1;
            for (let item of historyData) {
                if (item.lotteryDrawNum == prevIssue) {
                    drawalInfo = item;
                    break;
                }
            }
        } else {
            drawalInfo = historyData[0];
            issue = parseInt(drawalInfo.lotteryDrawNum) + 1;
        }
        let filePath = path.join(import.meta.dirname, `../data/dlt/order/${issue}.json`);
        if (fs.existsSync(filePath)) {
            return false;
        }
        let data = {
            "prevDrawalInfo": drawalInfo,
            "drawalInfo": {
                "lotteryDrawNum": issue,
                "lotteryDrawResult": "",
                "lotteryDrawTime": ""
            },
            "orderList": []
        };;
        let orderItem = {}, timeText = dayjs().format('YYYY-MM-DD HH:mm:ss');
        for (let lv = 1; lv <= 3; lv++) {
            orderItem = {
                "title": `定时任务，列方案-级别${lv}，初选模式，共10注`,
                "data": [],
                "remark": "",
                "prizeInfo": {
                    "value": 0,
                    "text": "未中奖",
                    "front": 0,
                    "back": 0,
                    "money": 0,
                    "moneyText": "-"
                },
                "time": timeText
            }
            for (let i = 1; i <= 10; i++) {
                orderItem.data.push(this.generateOrder(true, lv));
            }
            data.orderList.push(...orderItem);
        }

        for (let lv = 1; lv <= 3; lv++) {
            orderItem = {
                "title": `定时任务，前后区方案-级别${lv}，初选模式，共10注`,
                "data": [],
                "remark": "",
                "prizeInfo": {
                    "value": 0,
                    "text": "未中奖",
                    "front": 0,
                    "back": 0,
                    "money": 0,
                    "moneyText": "-"
                },
                "time": timeText
            }
            for (let i = 1; i <= 10; i++) {
                orderItem.data.push(this.generateOrder(false, lv));
            }
            data.orderList.push(...orderItem);
        }
        fs.writeFileSync(filePath, JSON.parse(data));
        return true;
    }
    drawalOrder(issue = '') {
        let drawalInfo = null, historyData = this.getData();
        if (issue) {
            for (let item of historyData) {
                if (item.lotteryDrawNum == issue) {
                    drawalInfo = item;
                    break;
                }
            }
        } else {
            drawalInfo = historyData[0];
            issue = drawalInfo.lotteryDrawNum;
        }
        let filePath = path.join(import.meta.dirname, `../data/dlt/order/${issue}.json`);
        if (!fs.existsSync(filePath)) {
            return false;
        }
        let data = JSON.parse(fs.readFileSync(filePath));
        data.drawalInfo.lotteryDrawResult = drawalInfo.lotteryDrawResult;
        data.drawalInfo.lotteryDrawTime = drawalInfo.lotteryDrawTime;
        let arrTemp = drawalInfo.lotteryDrawResult.split(' ');
        let resultArr = [arrTemp.slice(0, split_index), arrTemp.slice(split_index + 1)];
        let itemArr=[],intersectArr=[];
        for (let item of data.orderList) {
            item.data.forEach(orderText => {
                arrTemp=orderText.split(' ');
                itemArr = [arrTemp.slice(0,split_index),arrTemp.slice(split_index + 1)];
                intersectArr=[itemArr[0].filter(num => resultArr[0].includes(num)),itemArr[1].filter(num => resultArr[1].includes(num))];
                drawalOrderList.push({
                    order:orderText, FrontWinNums:intersectArr[0], BackWinNums:intersectArr[1],prizeInfo: {
                        "value": 1,
                        "text": "一等奖",
                        "front": 6,
                        "back": 1,
                        "money": 5000000,
                        "moneyText": "500万"
                    },
                })
            })
        }

        fs.writeFileSync(filePath, JSON.parse(data));
        return true;
    }
    _getOrderTemplate() {
        return {
            "prevDrawalInfo": {
                "lotteryDrawNum": 25098,
                "lotteryDrawResult": "",
                "lotteryDrawTime": ""
            },
            "drawalInfo": {
                "lotteryDrawNum": 25099,
                "lotteryDrawResult": "",
                "lotteryDrawTime": ""
            },
            "orderList": [
                {
                    "title": "定时任务/人工选号/AI选号，列方案x1，初选/优选模式",
                    "data": [
                        "03 13 11 11 21 08 12"
                    ],
                    "remark": "沙雕了，总结规律是。。。",
                    "prizeInfo": {
                        "value": 1,
                        "text": "一等奖",
                        "front": 6,
                        "back": 1,
                        "money": 5000000,
                        "moneyText": "500万"
                    },
                    "time": "2025-05-01 21:30:00"
                }
            ]
        };
    }
}
export default DltModel;